package com.geezdata.cps.base.shiro;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.geezdata.cps.base.cache.redis.RedisObjectSerializer;
import com.geezdata.cps.base.config.ApiConfig;
import com.geezdata.cps.base.redis.MyBatisRedisCache;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {
	public static final Integer DEFAULT_MAX_TOTAL = 200;
	public static final Integer DEFAULT_MIN_TOTAL = 100;
    public static final Integer DEFAULT_MAX_IDLE = 100;
    public static final Integer DEFAULT_MAX_WAIT_MILLS = 10000;
    public static final Boolean DEFAULT_TEST_ON_BORROW = true;
    public static final Boolean DEFAULT_TEST_ON_RETURN = false;
    public static final Boolean DEFAULT_TEST_WHILE_IDLE = true;
    
    
    @Bean 
    public RedisConnectionFactory redisConnectionFactory(ApiConfig apiConfig) {
    	JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(DEFAULT_MAX_TOTAL);
        config.setMaxIdle(DEFAULT_MAX_IDLE);
        config.setMinIdle(DEFAULT_MIN_TOTAL);
        config.setMaxWaitMillis(DEFAULT_MAX_WAIT_MILLS);
        config.setTestOnBorrow(DEFAULT_TEST_ON_BORROW);
        config.setTestOnReturn(DEFAULT_TEST_ON_RETURN);
        config.setTestWhileIdle(DEFAULT_TEST_WHILE_IDLE);
        
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(config);
    	jedisConnectionFactory.setHostName(apiConfig.getRedisHost());
    	jedisConnectionFactory.setPort(apiConfig.getRedisPort());
    	jedisConnectionFactory.setPassword(apiConfig.getRedisPassword());
    	jedisConnectionFactory.afterPropertiesSet();
    	MyBatisRedisCache.setJedisConnectionFactory(jedisConnectionFactory);
    	
    	return jedisConnectionFactory;
    }
    
    @Bean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }
}
